import { userList, userCount } from "@/request/api"

// 封装一个state接口
interface userState {
    userlist: Array<object>
}

const state = {
    userlist: [],
    total: 0,
    size: 2,
    page: 1
}

const getters = {
    getUserlist(state: userState) {
        return state.userlist
    },
    getCount(state: any) {
        return state.total
    },
    getSize(state: any) {
        return state.size
    }
}

const mutations = {
    REQ_USERLIST(state: userState, payload: any) {
        state.userlist = payload
    },
    REQ_COUNT(state: any, payload: any) {
        state.total = payload
    },
    REQ_PAGE(state: any, payload: any) {
        state.page = payload
    }
}

const actions = {
    UserListActions(context: any) {
        console.log(context);
        userList({
            size: context.state.size,
            page: context.state.page
        }).then((res: any) => {
            console.log(res, '管理员列表');
            if (res.code == 200) {
                let list = res.list ? res.list : []
                if (context.state.page != 1 && list.length == 0) {
                    context.dispatch('changePageAction', context.state.page - 1)
                }
                context.commit('REQ_USERLIST', list)
            }
        })
    },
    changeCountAction(context: any) {
        userCount().then((res: any) => {
            console.log(res, '总条数');
            if (res.code == 200) {
                context.commit('REQ_COUNT', res.list[0].total)
            }
        })
    },
    changePageAction(context: any, payload: any) {
        console.log(context, 'context');
        context.commit('REQ_PAGE', payload)
        context.dispatch('UserListActions')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}